#!/usr/bin/env python3
"""
数据导出和报告生成模块
Data Export and Report Generation Module
"""

import csv
import json
import sqlite3
import os
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional
import pandas as pd
from dataclasses import dataclass, asdict
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np

@dataclass
class ExportConfig:
    """导出配置"""
    export_type: str  # csv, json, excel, pdf
    date_range: tuple  # (start_date, end_date)
    data_types: List[str]  # ['sensor', 'irrigation', 'pest', 'weather', 'device']
    include_charts: bool
    file_path: str

class DataExporter:
    """数据导出器"""
    
    def __init__(self, db_path: str = "enhanced_agriculture.db"):
        self.db_path = db_path
        self.export_formats = {
            'csv': self.export_to_csv,
            'json': self.export_to_json,
            'excel': self.export_to_excel,
            'pdf': self.export_to_pdf
        }
    
    def export_data(self, config: ExportConfig) -> bool:
        """导出数据"""
        try:
            if config.export_type in self.export_formats:
                return self.export_formats[config.export_type](config)
            else:
                raise ValueError(f"不支持的导出格式: {config.export_type}")
        except Exception as e:
            print(f"数据导出失败: {e}")
            return False
    
    def get_sensor_data(self, start_date: datetime, end_date: datetime) -> List[Dict]:
        """获取传感器数据"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT * FROM sensor_data 
            WHERE timestamp BETWEEN ? AND ?
            ORDER BY timestamp
        ''', (start_date.isoformat(), end_date.isoformat()))
        
        columns = [desc[0] for desc in cursor.description]
        rows = cursor.fetchall()
        conn.close()
        
        return [dict(zip(columns, row)) for row in rows]
    
    def get_irrigation_data(self, start_date: datetime, end_date: datetime) -> List[Dict]:
        """获取灌溉数据"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT * FROM irrigation_log 
            WHERE timestamp BETWEEN ? AND ?
            ORDER BY timestamp
        ''', (start_date.isoformat(), end_date.isoformat()))
        
        columns = [desc[0] for desc in cursor.description]
        rows = cursor.fetchall()
        conn.close()
        
        return [dict(zip(columns, row)) for row in rows]
    
    def get_pest_data(self, start_date: datetime, end_date: datetime) -> List[Dict]:
        """获取病虫害数据"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT * FROM pest_detection 
            WHERE timestamp BETWEEN ? AND ?
            ORDER BY timestamp
        ''', (start_date.isoformat(), end_date.isoformat()))
        
        columns = [desc[0] for desc in cursor.description]
        rows = cursor.fetchall()
        conn.close()
        
        return [dict(zip(columns, row)) for row in rows]
    
    def get_weather_data(self, start_date: datetime, end_date: datetime) -> List[Dict]:
        """获取天气数据"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT * FROM weather_forecast 
            WHERE timestamp BETWEEN ? AND ?
            ORDER BY timestamp
        ''', (start_date.isoformat(), end_date.isoformat()))
        
        columns = [desc[0] for desc in cursor.description]
        rows = cursor.fetchall()
        conn.close()
        
        return [dict(zip(columns, row)) for row in rows]
    
    def get_device_data(self, start_date: datetime, end_date: datetime) -> List[Dict]:
        """获取设备数据"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT * FROM device_status 
            WHERE timestamp BETWEEN ? AND ?
            ORDER BY timestamp
        ''', (start_date.isoformat(), end_date.isoformat()))
        
        columns = [desc[0] for desc in cursor.description]
        rows = cursor.fetchall()
        conn.close()
        
        return [dict(zip(columns, row)) for row in rows]
    
    def collect_export_data(self, config: ExportConfig) -> Dict[str, List[Dict]]:
        """收集导出数据"""
        start_date, end_date = config.date_range
        data = {}
        
        data_getters = {
            'sensor': self.get_sensor_data,
            'irrigation': self.get_irrigation_data,
            'pest': self.get_pest_data,
            'weather': self.get_weather_data,
            'device': self.get_device_data
        }
        
        for data_type in config.data_types:
            if data_type in data_getters:
                data[data_type] = data_getters[data_type](start_date, end_date)
        
        return data
    
    def export_to_csv(self, config: ExportConfig) -> bool:
        """导出为CSV格式"""
        data = self.collect_export_data(config)
        
        # 为每种数据类型创建单独的CSV文件
        base_path = config.file_path.replace('.csv', '')
        
        for data_type, records in data.items():
            if records:
                file_path = f"{base_path}_{data_type}.csv"
                
                with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
                    if records:
                        fieldnames = records[0].keys()
                        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                        writer.writeheader()
                        writer.writerows(records)
        
        return True
    
    def export_to_json(self, config: ExportConfig) -> bool:
        """导出为JSON格式"""
        data = self.collect_export_data(config)
        
        # 添加元数据
        export_data = {
            'metadata': {
                'export_time': datetime.now().isoformat(),
                'date_range': {
                    'start': config.date_range[0].isoformat(),
                    'end': config.date_range[1].isoformat()
                },
                'data_types': config.data_types,
                'total_records': sum(len(records) for records in data.values())
            },
            'data': data
        }
        
        with open(config.file_path, 'w', encoding='utf-8') as jsonfile:
            json.dump(export_data, jsonfile, ensure_ascii=False, indent=2)
        
        return True
    
    def export_to_excel(self, config: ExportConfig) -> bool:
        """导出为Excel格式"""
        data = self.collect_export_data(config)
        
        with pd.ExcelWriter(config.file_path, engine='openpyxl') as writer:
            # 为每种数据类型创建工作表
            for data_type, records in data.items():
                if records:
                    df = pd.DataFrame(records)
                    df.to_excel(writer, sheet_name=data_type, index=False)
            
            # 创建摘要工作表
            summary_data = []
            for data_type, records in data.items():
                summary_data.append({
                    '数据类型': data_type,
                    '记录数量': len(records),
                    '开始时间': config.date_range[0].strftime('%Y-%m-%d %H:%M:%S') if records else '',
                    '结束时间': config.date_range[1].strftime('%Y-%m-%d %H:%M:%S') if records else ''
                })
            
            summary_df = pd.DataFrame(summary_data)
            summary_df.to_excel(writer, sheet_name='数据摘要', index=False)
        
        return True
    
    def export_to_pdf(self, config: ExportConfig) -> bool:
        """导出为PDF格式"""
        data = self.collect_export_data(config)
        
        with PdfPages(config.file_path) as pdf:
            # 创建报告封面
            self.create_report_cover(pdf, config)
            
            # 创建数据摘要页
            self.create_data_summary_page(pdf, data, config)
            
            # 如果包含图表，创建图表页面
            if config.include_charts:
                self.create_charts_pages(pdf, data, config)
            
            # 创建数据详情页面
            self.create_data_detail_pages(pdf, data, config)
        
        return True
    
    def create_report_cover(self, pdf, config: ExportConfig):
        """创建报告封面"""
        fig, ax = plt.subplots(figsize=(8.5, 11))
        ax.axis('off')
        
        # 标题
        ax.text(0.5, 0.8, '智慧农业系统数据报告', 
                ha='center', va='center', fontsize=28, fontweight='bold')
        
        # 报告信息
        report_info = f"""
        导出时间: {datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')}
        数据范围: {config.date_range[0].strftime('%Y-%m-%d')} 至 {config.date_range[1].strftime('%Y-%m-%d')}
        数据类型: {', '.join(config.data_types)}
        """
        
        ax.text(0.5, 0.5, report_info,
                ha='center', va='center', fontsize=14)
        
        # 添加装饰元素
        ax.text(0.5, 0.2, '🌱 Smart Agriculture Edge Control System 🌱',
                ha='center', va='center', fontsize=16, color='green')
        
        pdf.savefig(fig, bbox_inches='tight')
        plt.close(fig)
    
    def create_data_summary_page(self, pdf, data: Dict, config: ExportConfig):
        """创建数据摘要页"""
        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(11, 8.5))
        fig.suptitle('数据摘要统计', fontsize=16, fontweight='bold')
        
        # 数据量统计
        data_counts = [len(records) for records in data.values()]
        data_types = list(data.keys())
        
        ax1.bar(data_types, data_counts, color=['skyblue', 'lightgreen', 'orange', 'pink', 'lightcoral'])
        ax1.set_title('各类型数据记录数量')
        ax1.set_ylabel('记录数量')
        plt.setp(ax1.get_xticklabels(), rotation=45)
        
        # 数据分布饼图
        ax2.pie(data_counts, labels=data_types, autopct='%1.1f%%', startangle=90)
        ax2.set_title('数据类型分布')
        
        # 时间分布（以传感器数据为例）
        if 'sensor' in data and data['sensor']:
            sensor_data = data['sensor']
            timestamps = [datetime.fromisoformat(record['timestamp']) for record in sensor_data]
            
            # 按小时统计
            hourly_counts = {}
            for ts in timestamps:
                hour = ts.hour
                hourly_counts[hour] = hourly_counts.get(hour, 0) + 1
            
            hours = list(range(24))
            counts = [hourly_counts.get(h, 0) for h in hours]
            
            ax3.plot(hours, counts, marker='o')
            ax3.set_title('数据采集时间分布（按小时）')
            ax3.set_xlabel('小时')
            ax3.set_ylabel('记录数量')
            ax3.grid(True, alpha=0.3)
        
        # 统计信息表格
        stats_data = []
        for data_type, records in data.items():
            stats_data.append([
                data_type,
                len(records),
                records[0]['timestamp'] if records else '',
                records[-1]['timestamp'] if records else ''
            ])
        
        ax4.axis('tight')
        ax4.axis('off')
        table = ax4.table(cellText=stats_data,
                         colLabels=['数据类型', '记录数', '开始时间', '结束时间'],
                         cellLoc='center',
                         loc='center')
        table.auto_set_font_size(False)
        table.set_fontsize(9)
        table.scale(1.2, 1.5)
        ax4.set_title('详细统计信息')
        
        plt.tight_layout()
        pdf.savefig(fig, bbox_inches='tight')
        plt.close(fig)
    
    def create_charts_pages(self, pdf, data: Dict, config: ExportConfig):
        """创建图表页面"""
        # 传感器数据图表
        if 'sensor' in data and data['sensor']:
            self.create_sensor_charts_page(pdf, data['sensor'])
        
        # 设备状态图表
        if 'device' in data and data['device']:
            self.create_device_charts_page(pdf, data['device'])
        
        # 灌溉数据图表
        if 'irrigation' in data and data['irrigation']:
            self.create_irrigation_charts_page(pdf, data['irrigation'])
    
    def create_sensor_charts_page(self, pdf, sensor_data: List[Dict]):
        """创建传感器数据图表页"""
        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(11, 8.5))
        fig.suptitle('传感器数据趋势分析', fontsize=16, fontweight='bold')
        
        # 准备数据
        timestamps = [datetime.fromisoformat(record['timestamp']) for record in sensor_data]
        soil_moisture = [record['soil_moisture'] for record in sensor_data]
        air_temp = [record['air_temperature'] for record in sensor_data]
        humidity = [record['air_humidity'] for record in sensor_data]
        ph_values = [record['ph_value'] for record in sensor_data]
        
        # 土壤湿度趋势
        ax1.plot(timestamps, soil_moisture, 'b-', linewidth=2)
        ax1.set_title('土壤湿度变化趋势')
        ax1.set_ylabel('湿度 (%)')
        ax1.grid(True, alpha=0.3)
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
        plt.setp(ax1.get_xticklabels(), rotation=45)
        
        # 温度趋势
        ax2.plot(timestamps, air_temp, 'r-', linewidth=2)
        ax2.set_title('空气温度变化趋势')
        ax2.set_ylabel('温度 (°C)')
        ax2.grid(True, alpha=0.3)
        ax2.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
        plt.setp(ax2.get_xticklabels(), rotation=45)
        
        # 湿度分布
        ax3.hist(humidity, bins=20, color='skyblue', alpha=0.7, edgecolor='black')
        ax3.set_title('空气湿度分布')
        ax3.set_xlabel('湿度 (%)')
        ax3.set_ylabel('频次')
        
        # pH值变化
        ax4.plot(timestamps, ph_values, 'g-', linewidth=2)
        ax4.set_title('pH值变化趋势')
        ax4.set_ylabel('pH值')
        ax4.grid(True, alpha=0.3)
        ax4.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
        plt.setp(ax4.get_xticklabels(), rotation=45)
        
        plt.tight_layout()
        pdf.savefig(fig, bbox_inches='tight')
        plt.close(fig)
    
    def create_device_charts_page(self, pdf, device_data: List[Dict]):
        """创建设备状态图表页"""
        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(11, 8.5))
        fig.suptitle('设备状态分析', fontsize=16, fontweight='bold')
        
        # 设备健康度分布
        health_scores = [record['health_score'] for record in device_data]
        ax1.hist(health_scores, bins=15, color='lightgreen', alpha=0.7, edgecolor='black')
        ax1.set_title('设备健康度分布')
        ax1.set_xlabel('健康度分数')
        ax1.set_ylabel('设备数量')
        
        # 设备状态统计
        status_counts = {}
        for record in device_data:
            status = record['status']
            status_counts[status] = status_counts.get(status, 0) + 1
        
        ax2.pie(status_counts.values(), labels=status_counts.keys(), autopct='%1.1f%%')
        ax2.set_title('设备状态分布')
        
        # 运行时间分析
        operating_hours = [record['operating_hours'] for record in device_data]
        device_names = [record['device_name'] for record in device_data]
        
        ax3.barh(device_names[:10], operating_hours[:10])  # 只显示前10个设备
        ax3.set_title('设备运行时间 (Top 10)')
        ax3.set_xlabel('运行小时数')
        
        # 健康度趋势（如果有时间序列数据）
        timestamps = [datetime.fromisoformat(record['timestamp']) for record in device_data]
        ax4.scatter(timestamps, health_scores, alpha=0.6)
        ax4.set_title('设备健康度时间趋势')
        ax4.set_ylabel('健康度分数')
        ax4.grid(True, alpha=0.3)
        ax4.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
        plt.setp(ax4.get_xticklabels(), rotation=45)
        
        plt.tight_layout()
        pdf.savefig(fig, bbox_inches='tight')
        plt.close(fig)
    
    def create_irrigation_charts_page(self, pdf, irrigation_data: List[Dict]):
        """创建灌溉数据图表页"""
        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(11, 8.5))
        fig.suptitle('灌溉系统分析', fontsize=16, fontweight='bold')
        
        # 灌溉频次统计
        timestamps = [datetime.fromisoformat(record['timestamp']) for record in irrigation_data]
        daily_counts = {}
        for ts in timestamps:
            date = ts.date()
            daily_counts[date] = daily_counts.get(date, 0) + 1
        
        dates = list(daily_counts.keys())
        counts = list(daily_counts.values())
        
        ax1.bar(dates, counts, color='lightblue')
        ax1.set_title('每日灌溉次数')
        ax1.set_ylabel('灌溉次数')
        plt.setp(ax1.get_xticklabels(), rotation=45)
        
        # 用水量分析
        water_amounts = [record.get('water_amount', 0) for record in irrigation_data]
        ax2.plot(timestamps, water_amounts, 'g-', marker='o', markersize=3)
        ax2.set_title('用水量变化趋势')
        ax2.set_ylabel('用水量 (L)')
        ax2.grid(True, alpha=0.3)
        plt.setp(ax2.get_xticklabels(), rotation=45)
        
        # 区域灌溉分布
        zone_counts = {}
        for record in irrigation_data:
            zone = record['zone_id']
            zone_counts[zone] = zone_counts.get(zone, 0) + 1
        
        ax3.pie(zone_counts.values(), labels=zone_counts.keys(), autopct='%1.1f%%')
        ax3.set_title('各区域灌溉分布')
        
        # 灌溉持续时间分析
        durations = [record['duration'] for record in irrigation_data]
        ax4.hist(durations, bins=15, color='orange', alpha=0.7, edgecolor='black')
        ax4.set_title('灌溉持续时间分布')
        ax4.set_xlabel('持续时间 (分钟)')
        ax4.set_ylabel('频次')
        
        plt.tight_layout()
        pdf.savefig(fig, bbox_inches='tight')
        plt.close(fig)
    
    def create_data_detail_pages(self, pdf, data: Dict, config: ExportConfig):
        """创建数据详情页面"""
        for data_type, records in data.items():
            if records:
                self.create_data_table_page(pdf, data_type, records[:50])  # 只显示前50条记录
    
    def create_data_table_page(self, pdf, data_type: str, records: List[Dict]):
        """创建数据表格页面"""
        fig, ax = plt.subplots(figsize=(11, 8.5))
        fig.suptitle(f'{data_type} 数据详情 (前50条记录)', fontsize=16, fontweight='bold')
        
        ax.axis('tight')
        ax.axis('off')
        
        # 准备表格数据
        if records:
            headers = list(records[0].keys())
            table_data = []
            
            for record in records:
                row = []
                for header in headers:
                    value = record[header]
                    # 格式化数值
                    if isinstance(value, float):
                        row.append(f"{value:.2f}")
                    elif isinstance(value, str) and 'timestamp' in header.lower():
                        # 格式化时间戳
                        try:
                            dt = datetime.fromisoformat(value)
                            row.append(dt.strftime('%m-%d %H:%M'))
                        except:
                            row.append(value)
                    else:
                        row.append(str(value))
                table_data.append(row)
            
            # 创建表格
            table = ax.table(cellText=table_data,
                           colLabels=headers,
                           cellLoc='center',
                           loc='center')
            
            table.auto_set_font_size(False)
            table.set_fontsize(8)
            table.scale(1.2, 1.5)
            
            # 设置表格样式
            for (i, j), cell in table.get_celld().items():
                if i == 0:  # 表头
                    cell.set_text_props(weight='bold')
                    cell.set_facecolor('#40466e')
                    cell.set_text_props(color='white')
                else:
                    cell.set_facecolor('#f8f9fa' if i % 2 == 0 else 'white')
        
        pdf.savefig(fig, bbox_inches='tight')
        plt.close(fig)

class ReportGenerator:
    """报告生成器"""
    
    def __init__(self, db_path: str = "enhanced_agriculture.db"):
        self.db_path = db_path
        self.exporter = DataExporter(db_path)
    
    def generate_daily_report(self, date: datetime) -> str:
        """生成日报告"""
        start_date = date.replace(hour=0, minute=0, second=0, microsecond=0)
        end_date = start_date + timedelta(days=1)
        
        file_path = f"daily_report_{date.strftime('%Y%m%d')}.pdf"
        
        config = ExportConfig(
            export_type='pdf',
            date_range=(start_date, end_date),
            data_types=['sensor', 'irrigation', 'pest', 'device'],
            include_charts=True,
            file_path=file_path
        )
        
        if self.exporter.export_data(config):
            return file_path
        return None
    
    def generate_weekly_report(self, week_start: datetime) -> str:
        """生成周报告"""
        start_date = week_start.replace(hour=0, minute=0, second=0, microsecond=0)
        end_date = start_date + timedelta(weeks=1)
        
        file_path = f"weekly_report_{week_start.strftime('%Y%m%d')}.pdf"
        
        config = ExportConfig(
            export_type='pdf',
            date_range=(start_date, end_date),
            data_types=['sensor', 'irrigation', 'pest', 'weather', 'device'],
            include_charts=True,
            file_path=file_path
        )
        
        if self.exporter.export_data(config):
            return file_path
        return None
    
    def generate_monthly_report(self, year: int, month: int) -> str:
        """生成月报告"""
        start_date = datetime(year, month, 1)
        if month == 12:
            end_date = datetime(year + 1, 1, 1)
        else:
            end_date = datetime(year, month + 1, 1)
        
        file_path = f"monthly_report_{year:04d}{month:02d}.pdf"
        
        config = ExportConfig(
            export_type='pdf',
            date_range=(start_date, end_date),
            data_types=['sensor', 'irrigation', 'pest', 'weather', 'device'],
            include_charts=True,
            file_path=file_path
        )
        
        if self.exporter.export_data(config):
            return file_path
        return None
    
    def generate_custom_report(self, start_date: datetime, end_date: datetime, 
                             data_types: List[str], report_name: str = None) -> str:
        """生成自定义报告"""
        if not report_name:
            report_name = f"custom_report_{start_date.strftime('%Y%m%d')}_{end_date.strftime('%Y%m%d')}"
        
        file_path = f"{report_name}.pdf"
        
        config = ExportConfig(
            export_type='pdf',
            date_range=(start_date, end_date),
            data_types=data_types,
            include_charts=True,
            file_path=file_path
        )
        
        if self.exporter.export_data(config):
            return file_path
        return None

def create_export_dialog():
    """创建导出对话框"""
    import tkinter as tk
    from tkinter import ttk, filedialog, messagebox
    
    class ExportDialog:
        def __init__(self, parent=None):
            self.root = tk.Toplevel(parent) if parent else tk.Tk()
            self.root.title("数据导出")
            self.root.geometry("500x400")
            self.root.resizable(False, False)
            
            self.setup_ui()
            
        def setup_ui(self):
            # 导出格式选择
            format_frame = ttk.LabelFrame(self.root, text="导出格式", padding=10)
            format_frame.pack(fill='x', padx=10, pady=5)
            
            self.format_var = tk.StringVar(value="pdf")
            formats = [("PDF报告", "pdf"), ("Excel表格", "excel"), ("CSV文件", "csv"), ("JSON数据", "json")]
            
            for text, value in formats:
                ttk.Radiobutton(format_frame, text=text, variable=self.format_var, value=value).pack(anchor='w')
            
            # 数据类型选择
            data_frame = ttk.LabelFrame(self.root, text="数据类型", padding=10)
            data_frame.pack(fill='x', padx=10, pady=5)
            
            self.data_vars = {}
            data_types = [("传感器数据", "sensor"), ("灌溉记录", "irrigation"), 
                         ("病虫害检测", "pest"), ("天气数据", "weather"), ("设备状态", "device")]
            
            for text, value in data_types:
                var = tk.BooleanVar(value=True)
                self.data_vars[value] = var
                ttk.Checkbutton(data_frame, text=text, variable=var).pack(anchor='w')
            
            # 时间范围选择
            time_frame = ttk.LabelFrame(self.root, text="时间范围", padding=10)
            time_frame.pack(fill='x', padx=10, pady=5)
            
            self.time_var = tk.StringVar(value="today")
            time_options = [("今天", "today"), ("最近7天", "week"), ("最近30天", "month"), ("自定义", "custom")]
            
            for text, value in time_options:
                ttk.Radiobutton(time_frame, text=text, variable=self.time_var, value=value).pack(anchor='w')
            
            # 选项
            option_frame = ttk.LabelFrame(self.root, text="导出选项", padding=10)
            option_frame.pack(fill='x', padx=10, pady=5)
            
            self.include_charts_var = tk.BooleanVar(value=True)
            ttk.Checkbutton(option_frame, text="包含图表", variable=self.include_charts_var).pack(anchor='w')
            
            # 按钮
            button_frame = ttk.Frame(self.root)
            button_frame.pack(fill='x', padx=10, pady=10)
            
            ttk.Button(button_frame, text="导出", command=self.export_data).pack(side='right', padx=5)
            ttk.Button(button_frame, text="取消", command=self.root.destroy).pack(side='right', padx=5)
        
        def export_data(self):
            # 获取选择的数据类型
            selected_types = [key for key, var in self.data_vars.items() if var.get()]
            
            if not selected_types:
                messagebox.showwarning("警告", "请至少选择一种数据类型")
                return
            
            # 计算时间范围
            now = datetime.now()
            if self.time_var.get() == "today":
                start_date = now.replace(hour=0, minute=0, second=0, microsecond=0)
                end_date = start_date + timedelta(days=1)
            elif self.time_var.get() == "week":
                end_date = now
                start_date = end_date - timedelta(days=7)
            elif self.time_var.get() == "month":
                end_date = now
                start_date = end_date - timedelta(days=30)
            else:  # custom
                messagebox.showinfo("提示", "自定义时间范围功能待实现")
                return
            
            # 选择保存文件
            format_ext = self.format_var.get()
            file_types = {
                'pdf': [('PDF files', '*.pdf')],
                'excel': [('Excel files', '*.xlsx')],
                'csv': [('CSV files', '*.csv')],
                'json': [('JSON files', '*.json')]
            }
            
            file_path = filedialog.asksaveasfilename(
                defaultextension=f'.{format_ext}',
                filetypes=file_types[format_ext]
            )
            
            if not file_path:
                return
            
            # 执行导出
            try:
                config = ExportConfig(
                    export_type=format_ext,
                    date_range=(start_date, end_date),
                    data_types=selected_types,
                    include_charts=self.include_charts_var.get(),
                    file_path=file_path
                )
                
                exporter = DataExporter()
                if exporter.export_data(config):
                    messagebox.showinfo("成功", f"数据已成功导出到:\n{file_path}")
                    self.root.destroy()
                else:
                    messagebox.showerror("错误", "数据导出失败")
            except Exception as e:
                messagebox.showerror("错误", f"导出过程中发生错误:\n{str(e)}")
    
    return ExportDialog()

if __name__ == "__main__":
    # 测试导出功能
    create_export_dialog()